package controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;

import model.Car;
import model.Ipva;
import view.ServerViewPanelIpva;
import databaseController.DatabaseController;

public class ServerIpvaController {

	private ServerViewPanelIpva panel;
	
	public ServerIpvaController() {
		this.panel = new ServerViewPanelIpva();
		this.panel.getjComboBoxCar().setModel(new DefaultComboBoxModel(DatabaseController.getInstance().getCarsDatabase().toArray()));		
		this.panel.getjButtonConfirm().addActionListener(new ListenerConfirm());
		this.panel.getjButtonClear().addActionListener(new ListenerClear());
	}
	
	public ServerViewPanelIpva getPanel() {
		return this.panel;
	}
	
	private void clear() {
		ServerIpvaController.this.panel.getjTextFieldValue().setText("");
		ServerIpvaController.this.panel.getjTextFieldDate().setText("");
		ServerIpvaController.this.panel.getjCheckBoxPayed().setSelected(false);
		
		ServerIpvaController.this.panel.getjComboBoxCar().setSelectedItem(null);		
	}
	
	class ListenerConfirm implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			Float value = 0f;
			try {
				value = Float.parseFloat(ServerIpvaController.this.panel.getjTextFieldValue().getText());
			}
			catch (NumberFormatException e1) {}
			
			Car car = (Car) ServerIpvaController.this.panel.getjComboBoxCar().getSelectedItem();
			String date = ServerIpvaController.this.panel.getjTextFieldDate().getText();
			boolean payed = ServerIpvaController.this.panel.getjCheckBoxPayed().isSelected();			
			
			DatabaseController.getInstance().addIpva(new Ipva(car, value, date, payed));
			
			JOptionPane.showMessageDialog(null,
				    "Ipva cadastrado com sucesso!\n " , 
				    "Sucesso", JOptionPane.INFORMATION_MESSAGE);
			
			ServerIpvaController.this.clear();
			
			System.out.println("*=*   Ipva   *=*");
			System.out.println("Car: " + car);
			System.out.println("Value: " + value + "(" + payed + ")");
			System.out.println("Date: " + date);
			System.out.println("*=*   ------------------   *=*");
		}
	}
	
	class ListenerClear implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			ServerIpvaController.this.clear();			
		}
	}	
}
